<template>
  <div id="app">
    <router-view v-slot="{ Component }">
      <transition name="fade" mode="out-in">
        <component :is="Component" v-if="!$route.meta.keepAlive" />
        <keep-alive v-else>
          <component :is="Component" />
        </keep-alive>
      </transition>
    </router-view>
  </div>
</template>

<script setup>
import { onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 页面加载性能优化
let routeChanging = false
let loadingTimer = null
const MIN_LOADING_TIME = 200

// 路由变化处理
const startRouteChange = () => {
  if (loadingTimer) clearTimeout(loadingTimer)
  routeChanging = true
  document.body.classList.add('route-changing')
}

const endRouteChange = () => {
  if (routeChanging) {
    loadingTimer = setTimeout(() => {
      routeChanging = false
      document.body.classList.remove('route-changing')
    }, MIN_LOADING_TIME)
  }
}

// 注册路由监听
router.beforeEach(() => {
  startRouteChange()
  return true
})

router.afterEach(() => {
  endRouteChange()
})

onMounted(() => {
  // 初始化时，如果没有token且不在登录页，跳转到登录页
  const token = localStorage.getItem('token')
  if (!token && router.currentRoute.value.name !== 'login') {
    router.push('/login')
  }
  
  // 优化渲染性能
  document.addEventListener('visibilitychange', handleVisibilityChange)
})

onBeforeUnmount(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange)
  if (loadingTimer) clearTimeout(loadingTimer)
})

// 处理页面可见性变化，优化后台标签页性能
function handleVisibilityChange() {
  if (document.hidden) {
    // 页面隐藏时降低更新频率
    document.body.classList.add('page-hidden')
  } else {
    // 页面可见时恢复更新
    document.body.classList.remove('page-hidden')
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

/* 页面过渡效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 路由切换时的加载样式 */
.route-changing::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background: linear-gradient(to right, #409eff, #67c23a);
  animation: loading-progress 2s infinite;
  z-index: 9999;
}

/* 后台标签性能优化 */
.page-hidden * {
  animation-play-state: paused !important;
  transition: none !important;
}

@keyframes loading-progress {
  0% {
    width: 0;
    opacity: 1;
  }
  50% {
    width: 50%;
    opacity: 0.8;
  }
  100% {
    width: 100%;
    opacity: 0;
  }
}
</style>
